package com.zitronella.course.osseventmanager.mvc;

import com.zitronella.course.osseventmanager.service.EventService;
import com.zitronella.course.osseventmanager.domain.Event;
import com.zitronella.course.osseventmanager.domain.Position;
import com.zitronella.course.osseventmanager.domain.EventUser;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.net.BindException;
import java.text.SimpleDateFormat;
import java.text.ParseException;

/**
 * Created by IntelliJ IDEA.
 * User: Robin
 * Date: Mar 15, 2009
 * Time: 3:25:03 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@SessionAttributes(types = Event.class)
public class CreateEventController{

    private EventService eventService;

    @Autowired
    public void setEventService(EventService eventService) {
        this.eventService = eventService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields(new String[] {"id"});
    }

    @RequestMapping(value = "/event/new", method = RequestMethod.GET)
    public String setupForm(Model model) {
        model.addAttribute("event", new Event());
         
        return "event";
    }

    @RequestMapping(value = "/event/new", method = RequestMethod.POST)
    public String saveItem(@ModelAttribute Event event, BindingResult result, HttpSession session) throws ParseException {

        //if (StringUtils.isBlank(event.getName()))
          //  result.rejectValue("name", "required", "Required");

        if (!result.hasErrors()) {

            if (event != null) {
                session.setAttribute("event", event);
                event.setAdminUserAccountId(getEventUser(session).getEmail());
                eventService.createEvent(event);
                return "redirect:/controller/position/new";
            }
            return "redirect:/controller/events";
        } else {
            return "event";
        }
    }

    private EventUser getEventUser(HttpSession session) {
        EventUser testUser = new EventUser("robin@gmail.com","robin", "","");
        session.setAttribute("user",testUser);
        return (EventUser) session.getAttribute("user");
    }
}
